<?php

namespace App\Http\Backend\Middleware;

use App\Http\Models\Users;
use App\Http\Utils\Token;
use Closure;

class Authenticate
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */

    /**
     * Create a new middleware instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $token=$request->header('token');
        $token=Token::getInstance()->decode($token)->get(function ($token){
            return Users::query()->where('token','=',$token)->count();
        });
        if($token->getError()){
            return fail($token->getError());
        }
        $request->user_id=$token->getUserInfo()['id'];
        return $next($request);
    }
}
